/* eslint-disable vue/no-use-v-if-with-v-for */
<template>
  <div class="field-config">
    <div class="left container">
      <span class="title">基本字段</span>
      <draggable class="dragArea list-group" :list="baseFields" :sort="false" :group="{ name: 'fields', pull: 'clone', put: false }" :clone="cloneElement" @drop.native.stop.prevent="">
				<el-button class="list-group-item" :icon="'V7_iconfont ' + element.icon" @click.stop="addFields(element)" v-for="(element, index) in baseFields" :key="index">
					{{ element.name }}
				</el-button>
			</draggable>
      <template v-if="!isProduct">
        <span class="title title-adv">高级控件</span>
        <draggable class="dragArea list-group" :list="advFields" :sort="false" :group="{ name: 'fields', pull: 'clone', put: false }" :clone="cloneElement" @drop.native.stop.prevent="">
          <el-button class="list-group-item" :icon="'V7_iconfont ' + element.icon" @click.stop="addFields(element)" v-for="(element, index) in advFields" :key="index">
            {{ element.name }}
          </el-button>
        </draggable>
      </template>
    </div>
    <el-form class="center container" size="small" label-position="top">
      <draggable class="fields-panel" :list="list" :scroll-sensitivity="60" :scroll-speed="10" :scroll="true" drag-class="sortable-drag" :force-fallback="forceFallback" handle=".move" group="fields" @drop.native.stop.prevent="">
        <template v-if="list.length">
          <div class="fields-item move" :class="[element.businessId === activeWidgetConfigForm.businessId ? 'is-active main-background-color9' : '', element.fieldType === 'group' ? 'group-item' : '']" :style="{ width: fieldAttrWidth[element.width]}" v-for="(element, index) in list" :key="index" @click="changeFieldConfig(element, index)">
            <i class="V7_iconfont V7_iconV7tubiao_shanchutong fr oprate" @click.stop="deleteFields(element, index)"></i>
            <formItem :item="element" :isConfig="true" type="config" class="widget-show">
              <widget :item="element" :paste="false" :isConfig="true" :key="element.businessId" @attrFields="attrFields"></widget>
            </formItem>
          </div>
        </template>
        <div v-if="list.length === 0" class="empty">
					<span>点击左侧字段或拖动字段到此区域，进行添加</span>
				</div>
      </draggable>
    </el-form>
    <div class="right container">
			<div v-if="activeWidgetConfigForm.businessId">
        <commonPanel :dynamicFormList="dynamicFormList" :list="list" ref="commonPanel">
					<currentForm :fieldsList="list" :form="activeWidgetConfigForm" :formList="activeWidgetConfigFormList" @blur="inputBlur" @selectChange="selectChange" :key="activeWidgetConfigForm.businessId" @reverseCorrelation="reverseCorrelation"></currentForm>
			  </commonPanel>
      </div>
		</div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { baseFields } from './fieldType/baseFields';
import { widgetConfig as widget } from './form/widget';
import draggable from 'vuedraggable';
import { advFields } from './fieldType/advFields';
import formItem from './form/formItem.vue';
import { Element, fieldAttrMap } from './fieldType';
import { uuid, commonAction } from '@/utils/common';
import format, { productConfig } from './propertyPanel/propertyConfig';
import { busConfigStore } from '../store/busConfigStore';
import cloneDeep from 'lodash/cloneDeep';
import { currentForm } from './propertyPanel';
import commonPanel from './propertyPanel/commonPanel.vue'
import { fieldsMap } from './form/widget/associateUser/config'
@Component({
  name: 'fieldConfig',
  components: {
    currentForm,
    draggable,
    formItem,
    widget,
    commonPanel
  }
})
export default class extends Vue {
  [x: string]: any;
  @Prop({ default: false }) private isProduct!: any
  private activeIndex = -1
  private unwatch: any = null;
  // 拖动时自动滚动
  private forceFallback = false;
  private fieldType = ''; // 保存当前选中的字段类型
  public activeWidgetConfigForm: any = {};
  private dynamicFormList: any[] = []
  public activeWidgetConfigFormList: any[] = [];
  private baseFields = Object.freeze(baseFields);
  private advFields = Object.freeze(advFields);
  private get fieldTypeMap () {
    const obj = {}
    baseFields.forEach((item) => {
      obj[item.fieldType] = item
    })
    advFields.forEach((item) => {
      obj[item.fieldType] = item
    })
    return obj
  }

  private attrFields (val) {
    console.log(val)
  }

  private selectChange () {
    console.log('123')
  }

  private reverseCorrelation () {
    console.log('reverseCorrelation')
  }

  public save () {
    if (!this.list.length) {
      this.$message.error('至少保留一个字段')
      return false
    }
    const isValide = this.list.find((item) => {
      if (item.fieldType === 'cascadeSelect') {
        const hasV = item.cascadeOptions.find((one) => one.isDelete !== 1);
        if (!hasV) {
          this.$message.error('多级下拉字段，数据设置为空');
          return true;
        }
      } else if (item.fieldType === 'associateService' && !item.displayField.length) {
        this.$message.error('关联服务的展示字段不能为空');
        return true;
      } else if (item.fieldType === 'associateSpare' && !item.displayField.length) {
        this.$message.error('关联备件的展示字段不能为空');
        return true;
      } else if (item.fieldType === 'associateUser' && !item.displayField.length) {
        this.$message.error('关联用客户的展示字段不能为空');
        return true;
      }
    })
    if (isValide) {
      return false;
    }
    let list: any = []

    list = cloneDeep(this.list)
    const data = {
      fields: list.map((item, index) => {
        const { attrCode } = item
        item.businessId = attrCode
        delete item.attrCode
        return Object.assign({}, item, { sort: index + 1 })
      }),
      modelId: this.$route.params.businessId,
      dynamicFormList: (this.$refs as any).commonPanel.dynamicFormList
    }
    if (this.$route.params.businessId !== 'addService') {
      commonAction({ url: '/server-work/action/field/save', method: 'post', data }).then(res => {
        if (res.success) {
          this.$message.success('保存成功')
          busConfigStore.fieldsChange = false;
        }
      })
    } else {
      this.$message.success('请先创建模版基本信息！')
    }
  }

  private get fieldAttrWidth () {
    return fieldAttrMap.width
  }

  // 克隆表单
  public cloneElement ({ fieldType, name, prefix }: Element) {
    const index = busConfigStore.list.findIndex((item) => item.fieldType === 'associateUser')
    if (index > -1 && fieldType === 'associateUser') {
      this.$message.error('关联客户只允许添加一个')
      return undefined
    }
    let value = ''
    const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for (let i = 1; i <= 4; i++) {
      value = value + str.charAt(62 * Math.random())
    }
    const businessId = prefix + value + '_' + new Date().getTime();
    let obj = {} as any
    if (this.isProduct) {
      obj = productConfig[fieldType].formTemplate
    }
    return Object.assign(cloneDeep(format[fieldType].formTemplate), { businessId, attrCode: businessId }, obj);
  }

  // 添加的字段数组
  private get list () {
    return busConfigStore.list;
  }

  private addListWatch () {
    busConfigStore.fieldsChange = false;
    if (this.unwatch) {
      this.unwatch();
    }
    this.unwatch = this.$watch(
      'list',
      () => {
        busConfigStore.fieldsChange = true;
        this.unwatch();
      },
      { deep: true }
    );
  }

  private async getSheetConfig (sheetId) {
    const data = { modelId: this.$route.params.businessId, queryFieldType: 2, showDynamicForm: true }
    commonAction({ url: '/server-work/action/workOrderModel/getConfig', method: 'post', data }).then(res => {
      if (res.success) {
        // this.handleDynamicFormList(res.data.dynamicFormResVO?.list || [])
        this.dynamicFormList = res.data.dynamicFormResVO?.list || []
        busConfigStore.list = (res.data.fields || []).map(item => {
          const { businessId } = item
          return Object.assign({}, item, { attrCode: businessId })
        });
        this.addListWatch()
      }
    })
  }

  private handleDynamicFormList (list: any) {
    this.dynamicFormList = list.map(item => {
      if (item?.triggerTimeList.length) {
        this.$set(item, 'triggerTimeStatus', []);
        this.$set(item, 'fieldList', []);
        item.triggerTimeList.forEach(row => {
          if (row?.fieldList) {
            this.$set(item, 'fieldList', row.fieldList);
          }
          item.triggerTimeStatus.push(row.triggerTimeStatus)
        })
      }
      return item
    })
  }

  private beforeRouteEnter (to: any, from: any, next: any): void {
    next((vm) => {
      vm.getCustomerFields()
      vm.getSheetConfig(vm.$route.params.worksheetId);
    });
  }

  private getCustomerFields () {
    commonAction({ url: '/server-crm/action/config/customer/panel/detail', method: 'get' }).then(res => {
      if (res.success) {
        const cmap = {}
        busConfigStore.customerFields = res.data.fields.map(item => {
          cmap[item.field] = item.name
          return {
            label: item.name,
            value: item.field
          }
        })
        busConfigStore.customerFieldsMap = Object.assign({}, fieldsMap, cmap)
      }
    })
  }

  private deleteFields (element: Element, index: number) {
    this.$confirm('删除该字段后，表格下现有的记录数据将被删除，是否继续？', '确定删除字段吗', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.confirm(
        [],
        (fn) => {
          fn();
        },
        index,
        element
      );
    });
  }

  private confirm (deleleField, fn, index, element) {
    const del = () => {
      let deleteIndexArr = [index];
      if (deleleField && deleleField.length) {
        deleteIndexArr = [index, ...deleleField];
      }
      if (element.businessId === this.activeWidgetConfigForm.businessId) {
        this.activeWidgetConfigForm = {};
      }
      busConfigStore.list = busConfigStore.list.filter((item, key) => {
        return !deleteIndexArr.includes(key);
      });
    };
    fn(del);
  }

  // 添加字段
  private addFields (element: Element) {
    const index = busConfigStore.list.findIndex((item) => item.fieldType === 'associateUser')
    if (index > -1 && element.fieldType === 'associateUser') {
      this.$message.error('关联客户只允许添加一个')
      return false
    }
    const form = this.cloneElement(element);
    form.label = form.name;
    form.value = form.businessId;
    busConfigStore.list.splice(this.activeIndex + 1, 0, form)
    this.changeFieldConfig(form, this.activeIndex + 1);
  }

  private inputBlur (item) {
    if (item.name === 'name' && this.activeWidgetConfigForm.name === '') {
      this.activeWidgetConfigForm.name = format[this.activeWidgetConfigForm.fieldType].formTemplate.name;
    }
  }

  private async changeFieldConfig (element: Element, index: number) {
    const { fieldType } = element;
    this.fieldType = fieldType;
    this.activeIndex = index;
    this.activeWidgetConfigForm = element;
    switch (fieldType) {
      default:
        this.activeWidgetConfigFormList = this.productFormList(element.fieldType)
    }
  }

  private productFormList (fieldType: string) {
    if (this.isProduct) {
      return [...format[fieldType].formList, ...productConfig[fieldType].formList]
    } else {
      return format[fieldType].formList;
    }
  }
}
</script>
<style lang="stylus" scoped>
.field-config {
  display flex
  padding 0
  height calc(100% - 48px)
  box-sizing border-box
  background #fff
  .title {
    color #262626
    display block
    margin-bottom 8px
    font-size 14px
  }
  .title-adv {
    margin-top 24px
  }
  .container {
    height 100%
    overflow-y auto
    overflow-x hidden
    box-sizing border-box
    background #fff
  }
  .left {
    width 220px
    min-width 220px
    padding 19px 10px
    box-shadow: 1px 0px 4px 0px #e0e6f0;
    border-right: 1px solid #e0e6f0;
    .list-group {
      display flex
      flex-wrap wrap
      text-align left
      justify-content space-between
      /deep/span {
        flex-grow 1
        flex-shrink 0
        max-width calc(100% - 12px)
      }
    }
    .list-group-item {
      text-align: left;
      width: calc(50% - 6px);
      margin-bottom: 12px;
      padding: 8px;
      color: #595959;
      display: flex;
      align-items: center;
      border: 1px solid #E7E9ED;
      border-radius: 4px;
      box-sizing: border-box;
      &+.list-group-item {
        margin-left 0
        white-space normal
      }
    }
  }
  .center {
    flex-grow 1
    position relative
    // background rgba(0, 0, 0, 0.02)
    .sheet-title {
      padding 20px 12px 0
      margin 0 12px
      height 72px
      box-sizing border-box
      display flex
      align-items center
      box-shadow 0px 1px 0px rgba(0, 0, 0, 0.05)
      justify-content space-between
    }
    .sheet-name {
      font-size 20px
      font-weight 500
    }
    .fields-panel {
      height calc(100% - 0px)
      padding: 20px;
      overflow-y auto
      width 100%
      display inline-flex
      flex-wrap wrap
      align-content flex-start
      /deep/.el-form-item__content {
        line-height: inherit !important;
      }
      .oprate {
        margin-top 3px
        font-size 16px
        margin-left 16px
        color #666
        display block
        cursor pointer
      }
      .list-group-item {
        height min-content
      }
    }
    .fields-item {
      padding 16px 20px
      box-sizing border-box
      &.is-active {
        // background-color #E9EFFE
        border: 1px solid #008BEE;
        box-shadow: 0px 0px 7px 1px rgba(165,212,245,30%);
        border-radius: 4px;
        .oprate {
          display block
        }
      }
      &:hover {
        border-radius: 4px;
        border: 1px solid #008BEE;
        box-shadow: 0px 0px 7px 1px rgba(165,212,245,30%);
        .oprate {
          display block
        }
      }
    }
    .group-item {
      background-color: #008BEE !important;
      color: #fff;
      line-height: 1px;
      padding-right: 42px;
      .V7_iconV7tubiao_shanchutong {
        color #fff
      }
    }
    /deep/.el-form-item {
      margin-bottom 0
    }
    .empty {
      width 100%
      height calc(100% - 82px)
      position absolute
      text-align center
      flex-direction column
      justify-content center
      display flex
      .circle {
        display block
        margin 0 auto 16px
        width 210px
        height 140px
      }
    }
  }
  .right {
    // padding 16px 24px
    width 320px
    min-width 320px
    border-left 1px solid rgba(0, 0, 0, 0.05)
    .prompt {
      padding 12px 16px
      margin-bottom 24px
      border-radius 4px
      color $word3
      display flex
      font-size 14px
      align-items center
      background-color #FFF9E0
      border 1px solid #FFEDA6
      .iconfont {
        color #F5BC00
        font-size 24px
      }
      div {
        margin-left 16px
      }
      .content {
        font-size 12px
        display block
        color #666
        line-height 16px
      }
    }
    /deep/.el-form-item {
      margin-bottom 12px
      .el-form-item__content {
        line-height 0
      }
    }
  }
  .widget-show {
    /deep/.el-form-item__content {
      &:after {
        content ' '
        height 100%
        display block
        width 100%
        top 0
        z-index 200
        position absolute
      }
    }
  }
}
/deep/.sortable-drag {
  background #f5f5f5
}
</style>
